package com.weareint.common.advices;

import com.weareint.common.advices.utils.MethodTypeUtil;
import com.weareint.common.utils.IpUtil;
import com.weareint.common.TokenProvider;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.listener.AuditApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** <pre> 控制台操作日志切片 </pre> */
@Aspect
@Component
public class AnyOprAuditAspect implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired private TokenProvider tokenProvider;

    /** <pre> 开发包下的所有Controller </pre> */
    @Pointcut(
            "within(com.weareint..*)"
                    + " && within(@org.springframework.web.bind.annotation.RestController *)")
    public void controllerMethodsPointcut() {}

    /**
     * <pre>
     *      操作日志处理器
     * </pre>
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("controllerMethodsPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        AuditableParameter auditableParameter = createAuditableParameter(joinPoint);
        long start = System.currentTimeMillis();
        long end = 0;
        String exceptionStack = null;
        try {
            result = joinPoint.proceed();
            end = System.currentTimeMillis();
            return result;
        } catch (Throwable e) {
            StackTraceElement[] stackTrace = e.getStackTrace();
            StringBuilder buffer = new StringBuilder();
            for (StackTraceElement traceElement : stackTrace) {
                buffer.append(traceElement.toString()).append(System.lineSeparator());
            }
            exceptionStack = buffer.toString();
            throw e;
        } finally {
            // 推送操作事件
            Map<String, Object> data = new HashMap<>();
            data.put("args", auditableParameter.params);
            data.put("result", result);
            data.put("duration", new Duration(start, end));
            data.put("signature", auditableParameter.signature);
            data.put("ip", auditableParameter.ip);
            data.put("exceptionStack", exceptionStack);
            AuditEvent auditEvent =
                    new AuditEvent(
                            auditableParameter.principal,
                            auditableParameter.signature.getOprType(),
                            data);
            AuditApplicationEvent event = new AuditApplicationEvent(auditEvent);
            applicationEventPublisher.publishEvent(event);
        }
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * <pre>
     *      获取审计需要的参数
     * </pre>
     * @param joinPoint
     * @return
     */
    private AuditableParameter createAuditableParameter(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        AuditableParameter auditableParameter = new AuditableParameter();
        List<Object> params = new ArrayList<>();
        String principal = null;
        String ip = null;
        for (Object arg : args) {
            // 从请求的Request中取出Token与请求IP
            if (arg instanceof HttpServletRequest) {
                principal = tokenProvider.getTokenFromRequest((HttpServletRequest) arg);
                ip = IpUtil.getIpAddr((HttpServletRequest) arg);
            } else {
                params.add(arg);
            }
        }
        auditableParameter.ip = ip;
        auditableParameter.params = params;
        auditableParameter.principal = principal;
        auditableParameter.signature.setClazz(joinPoint.getSignature().getDeclaringTypeName());
        auditableParameter.signature.setMethod(joinPoint.getSignature().getName());
        auditableParameter.signature.setOprType(
                MethodTypeUtil.toType(auditableParameter.signature.getMethod()).getVal());
        return auditableParameter;
    }

    static class AuditableParameter {
        String ip;
        String principal;
        List<Object> params;
        Signature signature = new Signature();
    }
}
